//
//  LSResFirstController_version2.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/10/29.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSResFirstController_version2.h"

#import "LSBackButton.h"
#import "LSFirstCell.h"
#import "LSResListManager.h"
#import "LSResPackageController.h"
#import "ZBFtpTools.h"
#import "KZAlertView.h"
#import "LSFtpManager.h"
#import "KZSoundTool.h"

@interface LSResFirstController_version2 () <CAAnimationDelegate>

@property (nonatomic,strong) LSModelLSResList *model;

@property (nonatomic,strong) CAShapeLayer *lineLayer;

@property (nonatomic,strong) CAGradientLayer *gradientLayer;

@property (nonatomic,copy  ) NSArray *centerPoints;

@property (nonatomic,strong) LSSoundPlayer *soundPlayer;

@property (nonatomic,assign) BOOL isStopPlayer;

@property (nonatomic,assign) BOOL isNeedLoadData;


@end

@implementation LSResFirstController_version2
{
    NSTimer *_timer;
    UIImageView *_alertView;    // 定时提醒视图
    NSTimer *_audioTimer;
    NSInteger _audioCount; //等于3时不再开启定时器
    NSMutableArray *_temp;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.layer.contentsGravity = kCAGravityResizeAspectFill;
    self.view.layer.contents = (__bridge id)[UIImage imageNamed:@"LS-大背景"].CGImage;
    [self setupNaviUI];
    
    _isNeedLoadData = YES;
    
    [self.navigationController zk_registerBackInteractive:nil gestureConfig:nil];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setNaviAttributeWithTranslucent:YES stateBarLightContent:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"TimeRelease" object:nil];
    _isStopPlayer = NO;
    
    if (_isNeedLoadData) {
        
        [self loadData];
        
        _isNeedLoadData = NO;
    }
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.soundPlayer stop];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.soundPlayer) {
        [self.soundPlayer stop];
        _isStopPlayer = YES;
    }
    [_timer invalidate];
    _timer = nil;
}

#pragma mark - 定时器
- (void)timerAction {
    
    [_alertView gif:@"kz-点击"];
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_alertView stopAnimating];
        _alertView.animationImages = nil;
    });
}

- (void)audioTimeAction:(NSTimer*)timer {
  
    if (!_isStopPlayer) {
        LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_checkpoint];
        self.soundPlayer = player;
    }
    
    [_audioTimer invalidate];
    _audioTimer = nil;
    
    _audioCount = _audioCount+1;
    if (_audioCount<3) {
        CGFloat time ;
        if (_audioCount==1) {
            time = 3 * ([_temp[1] doubleValue] - [_temp[0] doubleValue]);
            
        } else {
            
            time = 3 * ([_temp[2] doubleValue] - [_temp[1] doubleValue]);
        }
        
        _audioTimer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(audioTimeAction:) userInfo:nil repeats:NO];
    }
    
}

#pragma mark - 视图
- (void)setupUI {
    
    [_gradientLayer removeFromSuperlayer];
    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    _lineLayer = CAShapeLayer.new;
    _lineLayer.lineWidth = W(3);
    _lineLayer.strokeStart = 0;
    _lineLayer.strokeEnd = 0;
    _lineLayer.strokeColor = [UIColor.whiteColor colorWithAlphaComponent:0.8].CGColor;
    _lineLayer.fillColor = UIColor.clearColor.CGColor;
    _lineLayer.lineDashPattern = @[@10, @4];
    [self.view.layer addSublayer:_lineLayer];
    
    NSMutableArray *temp = [NSMutableArray new];
    
    UIBezierPath *path = UIBezierPath.new;
    CGFloat radius = SCREEN_HEIGHT * 0.8 / 6;
    CGFloat width = W(80);
    CGFloat x = 0, y = 0;
    x = SCREEN_WIDTH / 2 + width / 2 + radius;
    y = SCREEN_HEIGHT / 2 - radius * 3;
    [path moveToPoint:CGPointMake(x, y)];
    // 左侧1/4圆
    x = x - radius;
    y = y;
    [path addArcWithCenter:CGPointMake(x, y) radius:radius startAngle:0 endAngle:M_PI * 0.5 clockwise:true];
    // 第1关的横线
    x = x - width;
    y = y + radius;
    [temp addObject:[NSValue valueWithCGPoint:CGPointMake(x + width / 2, y)]];
    [path addLineToPoint:CGPointMake(x, y)];
    // 左侧半圆
    x = x;
    y = y + radius;
    [path addArcWithCenter:CGPointMake(x, y) radius:radius startAngle:M_PI * 1.5 endAngle:M_PI * 0.5 clockwise:false];
    // 第2关的横线
    x = x + width;
    y = y + radius;
    [temp addObject:[NSValue valueWithCGPoint:CGPointMake(x - width / 2, y)]];
    [path addLineToPoint:CGPointMake(x, y)];
    // 右侧半圆
    x = x;
    y = y + radius;
    [path addArcWithCenter:CGPointMake(x, y) radius:radius startAngle:-M_PI * 0.5 endAngle:M_PI * 0.5 clockwise:true];
    // 第3关的横线
    x = x - width;
    y = y + radius;
    [temp addObject:[NSValue valueWithCGPoint:CGPointMake(x + width / 2, y)]];
    [path addLineToPoint:CGPointMake(x, y)];
    // 右侧1/4圆
    x = x;
    y = y + radius;
    [path addArcWithCenter:CGPointMake(x, y) radius:radius startAngle:-M_PI * 0.5 endAngle:-M_PI clockwise:false];
    
    _lineLayer.path = path.CGPath;
    
    _gradientLayer = [CAGradientLayer layer];
    _gradientLayer.bounds = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _gradientLayer.position = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
    _gradientLayer.colors = @[
                             (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0.0].CGColor,
                             (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0.9].CGColor,
                             (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0.9].CGColor,
                             (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0.9].CGColor,
                             (__bridge id)[[UIColor whiteColor] colorWithAlphaComponent:0.0].CGColor,
                             ];
    _gradientLayer.locations = @[@0.1, @0.2, @0.5, @0.8, @0.9];
    
    [self.view.layer insertSublayer:_gradientLayer atIndex:0];
    _gradientLayer.mask = _lineLayer;
    
    _centerPoints = temp.copy;
    
    NSString *typeID = _TypeID;
    NSArray *names1 = [NSArray array];
    NSArray *names2 = [NSArray array];
    if ([typeID isEqualToString:@"SE"]) {
        names1 = @[@"LS-慢速听力训练",@"LS-中速听力训练",@"LS-快速听力训练"];
        names2 = @[@"LS-慢速听力训练2",@"LS-中速听力训练2",@"LS-快速听力训练2"];
    } else if ([typeID isEqualToString:@"Sp"]||[typeID isEqualToString:@"Spn"]) {
        names1 = @[@"LS-慢速朗读训练",@"LS-中速朗读训练",@"LS-快速朗读训练"];
        names2 = @[@"LS-慢速朗读训练2",@"LS-中速朗读训练2",@"LS-快速朗读训练2"];
    }
    
    for (NSValue *pointValue in _centerPoints) {
        NSInteger index = [_centerPoints indexOfObject:pointValue];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = index + 10;
        [button addTarget:self action:@selector(pushAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(W(100));
            make.centerX.equalTo(self.view.mas_left).offset(pointValue.CGPointValue.x);
            make.centerY.equalTo(self.view.mas_top).offset(pointValue.CGPointValue.y);
        }];
        button.transform = CGAffineTransformMakeScale(0.0, 0.0);
        [button setBackgroundImage:[UIImage imageNamed:names1[index]] forState:UIControlStateNormal];
        if(index != (_model.PackageStage-1)) {
            
            button.userInteractionEnabled = NO;
            [button setBackgroundImage:[UIImage imageNamed:names2[index]] forState:UIControlStateNormal];
            if(index<_model.PackageStage-1) {
                [button setBackgroundImage:[UIImage imageNamed:@"LS-已通关"] forState:UIControlStateNormal];
            }
        } else {
            button.userInteractionEnabled = YES;
            
            // 小手
            _alertView = [UIImageView new];
            [self.view addSubview:_alertView];
            [_alertView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(button.mas_centerX);
                make.top.equalTo(button.mas_centerY);
                make.width.height.mas_equalTo(W(50));
            }];
            
            if (_timer) {
                [_timer invalidate];
                _timer = nil;
            }
            _timer = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(timerAction) userInfo:nil repeats:true];
            [_timer setFireDate:[NSDate dateWithTimeIntervalSinceNow:3]];
        }
        
        UILabel *label = [[UILabel alloc] init];
        label.tag = index + 20;
        label.text = [NSString stringWithFormat:@"第%li关", index + 1];
        label.font = FONT(18);
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor whiteColor];
        [self.view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(button.mas_bottom).offset(H(5));
            make.centerX.equalTo(button);
        }];
        label.transform = CGAffineTransformMakeTranslation(SCREEN_WIDTH / 2 * 1.2 * (index % 2 == 0 ? 1 : -1), 0);
    }
    
    // 跳出动画
    [self startPopAnimation];

}
- (void)setupNaviUI {
    
    NSString *text = @"听力能力强化训练";
    if ([_TypeID isEqualToString:@"Spn"]||[_TypeID isEqualToString:@"Sp"]) {
        text = @"朗读能力强化训练";
    }
    
    UIControl *backView = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    [backView addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backView];
    
    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    backImageView.image = [UIImage imageNamed:@"LS-nav_back"];
    [backView addSubview:backImageView];
    [backImageView sizeToFit];
    backImageView.centerY = backView.height / 2;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(backImageView.right+5, 0, [text getSizeOfBlodString:20].width, 40)];
    label.adjustsFontSizeToFitWidth = true;
    label.numberOfLines = 1;
    label.text = text;
    label.font = B_FONT(20);
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    [backView addSubview:label];
    
    backView.width = label.right;
    
    UIButton *noteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    noteButton.frame = CGRectMake(0, 0, 17, 17);
    [noteButton setImage:[UIImage imageNamed:@"kz-问号"] forState:UIControlStateNormal];
    [noteButton addTarget:self action:@selector(note) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:noteButton];
    
    
    
}

#pragma mark - 网络
- (void)loadData {
    LSResListManager *manager = [[LSResListManager alloc] init];
    NSDictionary *dict = @{@"StuID":DR_UserInfo.UserID,
                           @"StageNo":KGetUserDefaults(@"TestLayer"),
                           @"SchoolID":KGetUserDefaults(@"SchoolID"),
                           @"TypeID":_TypeID,
                           @"UpdateTime":_UpdateTime?_UpdateTime:@""
                           };
    
    [MBProgressHUD showLoadind:@"正在加载关卡，请稍候..."];
    manager.requestParam = @{@"DictString":[NSObject objectToJson:dict]};
    [manager requestWithCompltionSuccess:^(LSModelLSResList *model) {
        
        self.model = model;
        
        //初始化ftp配置
        [ZBFtpTools ZBFtp_setupInitWithHost:model.FtpServerAddress
                                       user:model.sUserName
                                        psw:model.sUserPwd];
        
        if([_model.PackageID isEqualToString:@""]) {
            _model.PackageStage = 100;//ID为空时，三关全部通关
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setupUI];
            [MBProgressHUD hideHud];
        });
        
    } failuer:^(NSString *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHud];
        });
    }];
}

#pragma mark - 设置与访问
- (void)setTypeID:(NSString *)TypeID {
    _TypeID = TypeID;
    NSLog(@"%ld===%ld====%f",LS_System.listenScore,LS_System.readScore,LS_System.lowSpeed);
    //  [self loadData];
}


#pragma mark - 事件
- (void)backAction:(UIButton*)sender {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (void)pushAction:(UIButton*)sender {
    
    [sender.layer removeAnimationForKey:@"BtnScale"];
    [self scaleAnimationWithView:sender];
}
// 问号备注
- (void)note {
    
    // 弹框提示
//    NSString *text = @"采用过关式认知训练方式,\n设置3道听力关卡,快速提升听力能力!";
//    if ([_TypeID isEqualToString:@"Spn"]||[_TypeID isEqualToString:@"Sp"]) {
//        text = @"采用过关式认知训练方式,\n设置3道朗读关卡,快速提升朗读能力!";
//    }
//    text = [text stringByAppendingString:@"\n\n您需要作答20道题完成第一轮训练,\n作答全部正确才能通关哟~\n\n论学习，小鸽是很严格的"];
    NSString *text = @"按照训练难度,小鸽设置了3道关卡,一气呵成答对20道才能顺利过关呦~";
    text = [text stringByAppendingString:@"\n\n论学习，小鸽是很严格的"];
    NSMutableAttributedString *subtitle = [[NSMutableAttributedString alloc] initWithString:text];
    
    KZAlertView *alert = [KZAlertView new];
    [alert showWithTitle:@"温馨提示" subtitle:subtitle submitTypes:@[@1] submitButtonsConfig:^(NSArray<UIButton *> *buttons) {
        
        [buttons.firstObject setTitle:@"好的" forState:UIControlStateNormal];
    } click:^(NSInteger index) {
        
    } destroyAtClickIndex:@[@0]];
}

#pragma mark - 动画
- (void)scaleAnimationWithView:(UIView*)view {
    CABasicAnimation*pulse = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    pulse.delegate = self;
    pulse.timingFunction= [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    pulse.duration = 0.2;
    pulse.repeatCount= 1;
    pulse.autoreverses= NO;
    pulse.fromValue= [NSNumber numberWithFloat:1.2];
    pulse.toValue= [NSNumber numberWithFloat:0.8];
    [view.layer addAnimation:pulse forKey:@"BtnScale"];
}
- (void)startPopAnimation {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        CABasicAnimation *ani = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        ani.toValue = @1;
        ani.duration = 3;
        ani.removedOnCompletion = false;
        ani.fillMode = kCAFillModeForwards;
        
        [_lineLayer addAnimation:ani forKey:@"ani"];
        
        CGFloat radius = SCREEN_HEIGHT * 0.8 / 6;
        CGFloat width = W(80);
        CGFloat c = 2 * M_PI * radius * 1.5 + width * 3;
        NSMutableArray *temp = [NSMutableArray new];
        CGFloat relative = 2 * M_PI * radius * 0.25 / c;
        [temp addObject:@(relative)];
        relative += (width / c + 2 * M_PI * radius * 0.5 / c);
        [temp addObject:@(relative)];
        relative += (width / c + 2 * M_PI * radius * 0.5 / c);
        [temp addObject:@(relative)];
        _temp = [NSMutableArray arrayWithArray:temp];
        
        _audioCount = 0;
        
        if (_audioTimer) {
            [_audioTimer invalidate];
            _audioTimer = nil;
        }
        _audioTimer = [NSTimer scheduledTimerWithTimeInterval:(3 * [temp[0] doubleValue]) target:self selector:@selector(audioTimeAction:) userInfo:nil repeats:NO];
        
        [UIView animateWithDuration:0.3 delay:(3 * [temp[0] doubleValue]) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            [self.view viewWithTag:10].transform = CGAffineTransformIdentity;
            [self.view viewWithTag:20].transform = CGAffineTransformIdentity;
            
        } completion:nil];
        
        [UIView animateWithDuration:0.3 delay:(3 * [temp[1] doubleValue]) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            [self.view viewWithTag:11].transform = CGAffineTransformIdentity;
            [self.view viewWithTag:21].transform = CGAffineTransformIdentity;
        } completion:nil];
        
        [UIView animateWithDuration:0.3 delay:(3 * [temp[2] doubleValue]) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
            [self.view viewWithTag:12].transform = CGAffineTransformIdentity;
            [self.view viewWithTag:22].transform = CGAffineTransformIdentity;
        } completion:nil];
    });
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * [temp[0] doubleValue] * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //[KZSoundTool playSound:KZSoundType_checkpoint];
//            if (!_isStopPlayer) {
//                LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_checkpoint];
//                self.soundPlayer = player;
//                [UIView animateWithDuration:0.3 delay:(3 * [temp[0] doubleValue]) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
//                    [self.view viewWithTag:10].transform = CGAffineTransformIdentity;
//                    [self.view viewWithTag:20].transform = CGAffineTransformIdentity;
//                } completion:nil];
//            }
//        });
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * [temp[1] doubleValue] * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //[KZSoundTool playSound:KZSoundType_checkpoint];
//            if (!_isStopPlayer) {
//                LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_checkpoint];
//                self.soundPlayer = player;
//                [UIView animateWithDuration:0.3 delay:(3 * [temp[0] doubleValue]) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
//                    [self.view viewWithTag:11].transform = CGAffineTransformIdentity;
//                    [self.view viewWithTag:21].transform = CGAffineTransformIdentity;
//                } completion:nil];
//            }
        
//        });
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * [temp[2] doubleValue] * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            //[KZSoundTool playSound:KZSoundType_checkpoint];
//            if (!_isStopPlayer) {
//                LSSoundPlayer *player = [[LSSoundPlayer alloc] initWithSound:KZSoundType_checkpoint];
//                self.soundPlayer = player;
//                [UIView animateWithDuration:0.3 delay:(3 * [temp[0] doubleValue]) usingSpringWithDamping:0.6 initialSpringVelocity:0 options:0 animations:^{
//                    [self.view viewWithTag:12].transform = CGAffineTransformIdentity;
//                    [self.view viewWithTag:22].transform = CGAffineTransformIdentity;
//                } completion:nil];
//            }
//        });
//    });
                   
}

#pragma mark - CAAnimationDelegate
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    if (flag) {
//        self.pushBlock();
        LSResPackageController *vc = [[LSResPackageController alloc] init];
        vc.model = self.model;
        [self.navigationController pushViewController:vc animated:YES];
        _isNeedLoadData = YES;
    }
}
@end
